<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2021/11/18
 * Time: 10:01
 */

namespace app\api\controller\android\v11;


use app\api\model\Capital;
use app\api\model\CapitalValue;
use app\api\model\Detailed;
use app\api\model\DetailedCategory;
use app\api\model\DetailedOption;
use app\api\model\DetailedOptionValue;
use app\api\model\EnvelopeRecords;
use app\api\model\Envelopes;
use app\api\model\OrderModel;
use app\api\model\VisaForm;
use think\Controller;
use app\api\model\Authority;
use app\api\model\Common;
use think\Request;
use think\Exception;
use app\index\model\Pdf;
use  app\api\model\Approval;
use Think\Db;
use app\api\model\Client;

class NewInfrastructure extends Controller
{
    protected $us;
    protected $pdf;

    public function _initialize()
    {
        $this->us  = Authority::check(1);
        $this->pdf = new Pdf();

    }

    /*
     * 获取配置清单
     */
    public function newDetailedList(DetailedCategory $detailedCategory)
    {
        $data         = Authority::param(['type']);
        $detailedList = $detailedCategory
            ->with(['detailedList','detailedList.detailedListValue'])
            ->where('detailed_category.is_enable', 1);
        if ($data['type'] == 0) {
            $detailedList->where('is_agency', 0);
        } else {
            $detailedList->where('is_agency', 1);
        }

        $detailedList = $detailedList->order('detailed_category.sort desc')
            ->select();
        foreach ($detailedList as $k => $ite) {
            if (!empty($ite['detailed_list'])) {
                foreach ($ite['detailed_list'] as $l => $value) {
                    $value['title'] = $ite['title'];
                    $value['types'] = 4;
                    if(!empty(array_column($value['detailed_list_value'],'option_value_title'))){
                        $value['detailedListValue']=$value['detailed_title'].','.implode(array_column($value['detailed_list_value'],'option_value_title'),',');

                    }else{
                        $value['detailedListValue']=$value['detailed_title'];
                    }
                    unset($value['detailed_list_value']);
                }

            }
            unset($detailedList[$k]['sort'], $detailedList[$k]['is_enable'], $detailedList[$k]['created_at'], $detailedList[$k]['updated_at'], $detailedList[$k]['type'], $detailedList[$k]['is_agency'], $detailedList[$k]['condition']);
        }

        r_date($detailedList, 200);
    }

    /*
     * 获取报价配置选项
     */
    public function getDetailedOption(DetailedOption $detailedOption)
    {
        $data                   = Authority::param(['id']);
        $getOptionValue['list'] = $detailedOption
            ->with(['detailedListOptionValues' => function ($query) use ($data) {
                $query->where('detailed_option_value.detailed_id', $data['id'])->group('detailed_option_value.option_value_id');
            }])
            ->where('condition', '<>', 2)
            ->order('option_id desc')
            ->select();

        foreach ($getOptionValue['list'] as $k => $value) {
            if (!empty($value['detailed_list_option_values'])) {
                $getOptionList['list'][] = $value;
            }
        }
        $getOptionList['PushList'] = db('detailed')
            ->join('detailed_relevance', 'detailed.detailed_id=detailed_relevance.relevance_detailed_id', 'left')
            ->join('detailed_category', 'detailed.detailed_category_id=detailed_category.id', 'left')
            ->field('detailed.detailed_title,detailed.detailed_id,detailed.agency,detailed.detailed_category_id,detailed.artificial,detailed_category.title')
            ->where('detailed_relevance.detailed_id', $data['id'])
            ->where('detailed.display', 1)
            ->select();
        foreach ($getOptionList['PushList'] as $k => $item) {
            $getOptionList['PushList'][$k]['types'] = 4;
        }
        $detailed=db('detailed')->join('unit','unit.id=detailed.un_id')->where('detailed_id',$data['id'])->field('rmakes,unit.title')->find();
        $getOptionList['remarks'] =$detailed['rmakes'];
        $getOptionList['title'] =$detailed['title'];
        r_date($getOptionList, 200);
    }

    /*
     * 报价模版
     */
    public function quotationTemplate()
    {
        $template = db('user_config', config('database.zong'))->where('key', 'quotation_template')->where('status', 1)->value('value');
        r_date(json_decode($template, true), 200);
    }

    /*
     * 计算价格
     */
    public function getValuation(DetailedOptionValue $detailedOptionValue, Common $common, Capital $capital)
    {
        $data = Authority::param(['data', 'id', 'types', 'capital_id']);
        if ($data['types'] == 4 || $data['types'] == 1) {
            $detailedValue = $common->newCapitalPrice($detailedOptionValue, $data['id'], json_decode($data['data'], true));
            if (!$detailedValue['code']) {
                r_date([], 300, $detailedValue['msg']);
            }
            $detailedValueList = $detailedValue['data'];
        } else {
            if ($data['types'] == 0) {
                $product_chan               = db('product_chan')->where('product_id', $data['id'])->find();
                $detailedValueList['sum']   = $product_chan['prices'];
                $detailedValueList['price'] = $product_chan['price_rules'];
                $detailedValueList['unit']  = $product_chan['price_rules'];

            } elseif ($data['types'] == 2) {
                $capitalIdFind              = $capital->QueryOne($data['capital_id']);
                $detailedValueList['sum']   = $capitalIdFind['un_Price'];
                $detailedValueList['price'] = [];
                $detailedValueList['unit']  = $capitalIdFind['company'];

            }
        }

        r_date(['price' => $detailedValueList['sum'], 'artificial' => $detailedValueList['price'], 'unTitle' => $detailedValueList['unit']], 200);
    }

    /*
     * 基建添加
     */
    public function addInfrastructure(Common $common, Capital $capital, DetailedOptionValue $detailedOptionValue, CapitalValue $capitalValue, OrderModel $orderModel)
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $cap = '';
            $orderModel->MultiTableUpdate($data['order_id'], 0);
            if ($data['company']) {
                $op = json_decode($data['company'], true);
                foreach ($op as $ke => $v) {
                    $ValueList = $v['specsList'];
                    if ($v['types'] == 4) {
                        $ValueId      = array_column($ValueList, 'option_value_id');
                        $CapitalPrice = $common->newCapitalPrice($detailedOptionValue, $v['product_id'], $ValueId);
                        if (!$CapitalPrice['code']) {
                            throw new Exception($CapitalPrice['msg']);
                        }
                        $CapitalPriceSection      = $capital->priceSection($CapitalPrice['data']['price'], $CapitalPrice['data']['artificial'], $CapitalPrice['data']['sum'], $CapitalPrice['data']['sumMast'], $v['fang']);
                        $data['sumMast']          = $CapitalPriceSection[2];
                        $data['sum']              = $CapitalPriceSection[3];
                        $data['price']            = $CapitalPrice['data']['price'];
                        $data['artificial']       = $CapitalPrice['data']['artificial'];
                        $data['categoryTitle']    = $CapitalPrice['data']['categoryTitle'];
                        $data['toPrice']          = $CapitalPriceSection[1];
                        $data['labor_cost_price'] = $CapitalPriceSection[0];
                        $id                       = $capital->newlyAdded($data, $v, 0);
                        foreach ($v['specsList'] as $item) {
                            $capitalValue->Add($item, $id);
                        }

                        if ($v['agency'] == 1) {
                            $p1[] = $CapitalPriceSection[1];
                        } else {
                            $p[] = $CapitalPriceSection[1];
                        }
                    } else {
                        if (!empty($ValueList)) {
                            throw new Exception('请检查参数');
                        }
                        if ($v['types'] == 0) {
                            $product_chan               = db('product_chan')->where('product_id', $v['product_id'])->find();
                            $product_chan['artificial'] = $product_chan['prices'];
                            $product_chan['rmakes']     = $product_chan['price_rules'];
                            $type                       = 0;
                        } elseif ($v['types'] == 1) {
                            $product_chan = db('detailed')->where('detailed_id', $v['product_id'])->find();
                            $type         = 1;
                        } elseif ($v['types'] == 2) {
                            $product_chan['artificial'] = $v['prices'];
                            $product_chan['rmakes']     = isset($v['remarks']) ? $v['remarks'] : '';
                            $type                       = 2;
                        }

                        $id = $capital->oldAdded($product_chan, $v, $data['order_id'], $type, 0);

                        if ($v['agency'] == 1) {
                            $p1[] = $v['fang'] * $v['prices'];
                        } else {
                            $p[] = $v['fang'] * $v['prices'];
                        }
                    }

                    if (!empty($id)) {
                        $cap        .= $id . ',';
                        $c          = substr($cap, 0, -1);
                        $standardId = json_decode($data['standardId'], true);
                        if (isset($data['schemeId'])) {
                            foreach ($standardId as $item) {
                                foreach ($item['data'] as $value) {
                                    if ($v['product_id'] == $item['auxiliary_id']) {
                                        $auxiliary_project_list = db('auxiliary_project_list')->insertGetId(['auxiliary_id' => $value['id'], 'capital_id' => $id, 'order_id' => $data['order_id'], 'created_time' => time()]);
                                        foreach ($value['data'] as $datum) {
                                            if ($datum['isChoose']) {
                                                db('auxiliary_delivery_schedule')->insertGetId(['auxiliary_interactive_id' => $datum['id'], 'auxiliary_project_list_id' => $auxiliary_project_list]);
                                            }

                                        }
                                    }
                                }

                            }
                        } else {
                            foreach ($standardId as $item) {
                                foreach ($item['auxiliaryInteractiveId'] as $value) {
                                    if ($v['product_id'] == $value['detailed_id']) {
                                        $auxiliary_project_list = db('auxiliary_project_list')->insertGetId(['auxiliary_id' => $item['id'], 'capital_id' => $id, 'order_id' => $data['order_id'], 'created_time' => time()]);
                                        foreach ($item['data'] as $datum) {
                                            if ($datum['isChoose']) {
                                                db('auxiliary_delivery_schedule')->insertGetId(['auxiliary_interactive_id' => $datum['id'], 'auxiliary_project_list_id' => $auxiliary_project_list]);
                                            }

                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (isset($data['schemeId']) && $data['schemeId'] != 0) {
                db('scheme_use', config('database.zong'))->insert(['plan_id' => $data['schemeId'], 'user_id' => $this->us['user_id'], 'creation_time' => time(), 'city' => config('cityId'), 'order_id' => $data['order_id']]);
            }

            //总金额
            if (isset($p) && !empty($p)) {
                $o = round(array_sum($p), 2);
//                if (($o * config('give_money')) < $data['give_money']) {
//                    throw  new  Exception('优惠金额不能大于订单总价的10%');
//                }
            } else {
                if ($data['give_money'] != 0) {
                    throw new Exception('主合同没有清单');
                }
                if ($data['expense'] != 0) {
                    throw new Exception('主合同没有清单');
                }

            }
            if (isset($p1) && !empty($p1)) {
//                $o = round(array_sum($p1), 2);
//                if (($o * config('give_money')) < $data['purchasing_discount']) {
//                    throw  new  Exception('优惠金额不能大于代购订单总价的10%');
//                }
            } else {
                if ($data['purchasing_discount'] != 0) {
                    throw new Exception('代购合同没有清单');
                }
                if ($data['purchasing_expense'] != 0) {
                    throw new Exception('主合同没有清单');
                }

            }

            $envelopes = db('envelopes')->insertGetId(['wen_a' => $data['wen_a'],//一级分类
                'give_b' => !empty($data['give_a']) ? substr($data['give_a'], 0, -1) : '', 'ordesr_id' => $data['order_id'], 'gong' => $data['gong'], 'give_remarks' => $data['give_remarks'],//备注
                'give_money' => $data['give_money'],//优惠金额
                'capitalgo' => !empty($data['capitalgo']) ? serialize(json_decode($data['capitalgo'], true)) : '', 'project_title' => $data['project_title'], 'expense' => !empty($data['expense']) ? $data['expense'] : 0, 'purchasing_discount' => $data['purchasing_discount'], 'purchasing_expense' => !empty($data['purchasing_expense']) ? $data['purchasing_expense'] : 0, 'type' => 1,
                'created_time' => time()

            ]);

            $capital->whereIn('capital_id', $c)->update(['envelopes_id' => $envelopes]);
            if (!empty($data['give_remarks'])) {
                db('through')->insertGetId(['mode' => '电话', 'amount' => 0, 'role' => 2, 'admin_id' => $this->us['user_id'], 'remar' => $data['give_remarks'], 'order_ids' => $data['order_id'], 'baocun' => 0, 'th_time' => time(), 'end_time' => 0, 'log' => '',//图片
                ]);
            }
            if (!empty($data['Warranty'])) {
                $Warranty = json_decode($data['Warranty'], true);
                foreach ($Warranty as $value) {
                    \db('warranty_collection')->insertGetId(['order_id' => $data['order_id'], 'warranty_id' => $value['warranty_id'], 'years' => $value['years'], 'creation_time' => time(), 'type' => 1, 'envelopes_id' => $envelopes]);
                }
            }

            $cap = db('order')->where(['order_id' => $data['order_id']])->field('ification,planned,appointment,telephone')->find();
            if (preg_match("/^1[345678]{1}\d{9}$/", $cap['telephone'])) {
                sendMsg($cap['telephone'], 8615);
            }
            db('order')->where(['order_id' => $data['order_id']])->update(['undetermined' => 0, 'ification' => 2, 'agency_address' => isset($data['agency_address']) ? $data['agency_address'] : '','order_agency'=>isset($p1) && !empty($p1)?1:0]);

            $pdf = $this->pdf->put($data['order_id'], 2, $cap);

            db('user')->where('user_id', $this->us['user_id'])->update(['lat' => $data['lat'], 'lng' => $data['lng']]);
            db('user', config('database.zong'))->where('user_id', $this->us['user_id'])->update(['lat' => $data['lat'], 'lng' => $data['lng']]);
            //页面停留时长
            db('stay')->insertGetId(['startTime' => substr($data['startTime'], 0, -3), 'endTime' => substr($data['endTime'], 0, -3), 'user_id' => $this->us['user_id'], 'order_id' => $data['order_id'], 'time' => time()]);
            //报价及时性
            db('quote')->insertGetId(['startTime' => $cap['appointment'], 'planned' => $cap['planned'], 'user_id' => $this->us['user_id'], 'order_id' => $data['order_id'], 'time' => time()]);

            if ($pdf) {
                db()->commit();
//                (new PollingModel())->automatic($data['order_id'], time());
                json_decode(sendOrder($data['order_id']), true);
                $clock_in = db('clock_in')->where('order_id', $data['order_id'])->value('order_id');
                if ($clock_in) {
                    $common->toExamine(1, $data['order_id'], 1, '');
                }
                r_date(null, 200);
            }

        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }

    }

    /**
     * 新版基建报价界面显示
     */
    public function InfrastructureEcho(Envelopes $envelopes)
    {
        $data      = Authority::param(['envelopes_id']);
        $envelopes = $envelopes->with(['CapitalList', 'CapitalList.specsList', 'OrderList'])
            ->where(['envelopes_id' => $data['envelopes_id']])
            ->find();
        foreach ($envelopes['capital_list'] as $k => $value) {
            $typeCapital ['approval.type']= 6;
            if ($value['modified_quantity'] != 0) {
                $typeCapital['approval.type']= array(['=',6],['=',8],'or');
            }
            $value['username'] = \db('approval', config('database.zong'))
                ->join(config('database.zong')['database'] . '.bi_user', 'approval.nxt_id=bi_user.user_id', 'left')
                ->where($typeCapital)
                ->where('approval.relation_id', $value->capital_id)
                ->order('approval.approval_id desc')
                ->value('bi_user.username');

        }
        $capitalList = $envelopes['capital_list'];
        $capital_id  = array_column($capitalList, 'capital_id');
        $po          = db('auxiliary_project_list')->whereIn('capital_id', $capital_id)->whereNull('delete_time')->field('auxiliary_id,id,capital_id')->select();

        $auxiliary_id          = array_column($po, 'auxiliary_id');
        $auxiliary_interactive = [];
        if (!empty($auxiliary_id)) {
            $auxiliary_interactive = db('auxiliary_interactive')->whereIn('id', $auxiliary_id)->field('id,title')->select();
        }
        $id                       = array_column($po, 'id');
        $auxiliaryInteractiveList = db('auxiliary_interactive')
            ->Join('auxiliary_delivery_schedule', 'auxiliary_delivery_schedule.auxiliary_interactive_id=auxiliary_interactive.id', 'left')
            ->whereIn('auxiliary_delivery_schedule.auxiliary_project_list_id', $id)
            ->whereNull('auxiliary_delivery_schedule.delete_time')
            ->field('auxiliary_interactive.id, auxiliary_interactive.title, auxiliary_delivery_schedule.id as auxiliary_delivery_schedule_id,auxiliary_delivery_schedule.auxiliary_project_list_id')->select();
        if (!empty($auxiliaryInteractiveList)) {
            $auxiliary_delivery_node = db('auxiliary_delivery_node')->whereIn('auxiliary_delivery_schedul_id', array_column($auxiliaryInteractiveList, 'auxiliary_delivery_schedule_id'))->field('state,node_id,auxiliary_delivery_schedul_id')->select();
        }
        $capitalListArray = [];
        $agency           = [];
        $sumlist          = [];
        foreach ($capitalList as $k => $item) {
            if ($item['agency'] == 1) {
                $agency[] = $item;
            } else {
                $sumlist[] = $item;
            }
            $auxiliary_ids = array_unique(array_column($po, 'id'));
            if ($po) {
                foreach ($po as $l => $key) {
                    if ($item['capital_id'] == $key['capital_id']) {
                        $capitalListArray[$k]['class_b']       = $item['projectTitle'];
                        $capitalListArray[$k]['auxiliary_id']  = $item['projectId'];
                        $capitalListArray[$k]['auxiliary_ids'] = implode($auxiliary_ids, ',');;
                        foreach ($auxiliary_interactive as $val) {
                            if ($key['auxiliary_id'] == $val['id']) {
                                $auxiliaryList[] = $val;
                            }

                        }
                        foreach ($auxiliaryList as $ls) {
                            $auxiliaryInteractiveListNode = [];

                            foreach ($auxiliaryInteractiveList as $p => $value) {
                                if ($key['id'] == $value['auxiliary_project_list_id'] && $key['id'] == $value['auxiliary_project_list_id']) {
                                    $state   = 3;
                                    $node_id = 0;
                                    foreach ($auxiliary_delivery_node as $node) {
                                        if ($node['auxiliary_delivery_schedul_id'] == $value['auxiliary_delivery_schedule_id'] && $key['id'] == $value['auxiliary_project_list_id']) {
                                            $auxiliaryNodeId   = array_column($auxiliary_delivery_node, 'state');
                                            $auxiliaryNodeNode = array_column($auxiliary_delivery_node, 'node_id');
                                            if ($auxiliaryNodeId) {
                                                if (in_array(2, $auxiliaryNodeId)) {
                                                    $state   = 2;
                                                    $node_id = implode(',', $auxiliaryNodeNode);
                                                } elseif (in_array(0, $auxiliaryNodeId)) {
                                                    $state   = 0;
                                                    $node_id = implode(',', $auxiliaryNodeNode);
                                                } else {
                                                    $state   = 1;
                                                    $node_id = implode(',', $auxiliaryNodeNode);
                                                }
                                            } else {
                                                $state   = 3;
                                                $node_id = 0;
                                            }
                                        }
                                    }
                                    $auxiliaryInteractiveListNode[$p]['state']                          = $state;
                                    $auxiliaryInteractiveListNode[$p]['node_id']                        = $node_id;
                                    $auxiliaryInteractiveListNode[$p]['id']                             = $value['id'];
                                    $auxiliaryInteractiveListNode[$p]['title']                          = $value['title'];
                                    $auxiliaryInteractiveListNode[$p]['auxiliary_delivery_schedule_id'] = $value['auxiliary_delivery_schedule_id'];
                                    $auxiliaryInteractiveListNode[$p]['auxiliary_project_list_id']      = $value['auxiliary_project_list_id'];
                                }

                                $ls['data'] = array_merge($auxiliaryInteractiveListNode);
                            }

                        }
                        $capitalListArray[$k]['data'][] = $ls;
                    }
                }

            }

        }

        $result   = array();
        $tageList = [];
        foreach ($envelopes['capital_list'] as $k => $v) {
            $v['specsList'] = $v['specs_list'];
            unset($v['specs_list']);
            $result[$v['categoryName']][] = $v;
        }
        foreach ($result as $k => $list) {
            $schemeTag['title'] = $k;
            $schemeTag['data']  = $result[$k];
            $tageList[]         = $schemeTag;
        }
        unset($envelopes['capital_list']);
        $envelopes['capital_list'] = $tageList;
        if (!empty($envelopes['give_b'])) {
            $envelopes['give_b'] = explode(',', $envelopes['give_b']);
        } else {
            $envelopes['give_b'] = null;
        }
//        if ($envelopes['capitalgo']) {
//            $envelopes['capitalgo'] = unserialize($envelopes['capitalgo']);
//        } else {
            $envelopes['capitalgo'] = null;
//        }
        //质保卡
        $warranty_collection = \db('warranty_collection')->where('warranty_collection.envelopes_id', $envelopes['envelopes_id'])->where('warranty_collection.pro_types', 0)->join('warranty', 'warranty.id=warranty_collection.warranty_id', 'left')->where('warranty_collection.order_id', $envelopes['ordesr_id'])->field('warranty.title,warranty_collection.years,warranty_collection.type,warranty_collection.warranty_id,warranty_collection.id')->select();

        $envelopes['agencysum'] = round(array_sum(array_column($agency, 'allMoney')), 2);
        $envelopes['sumlist']   = round(array_sum(array_column($sumlist, 'allMoney')), 2);


        r_date(['company' => $envelopes, 'warranty_collection' => $warranty_collection, 'capitalList' => array_merge($capitalListArray)], 200);
    }


    /**
     * 成交前基检删除
     */
    public function DeleteBeforeClosing(Capital $capital, OrderModel $orderModel, Envelopes $envelopes)
    {
        $data = Authority::param(['capital_id']);
        db()->startTrans();
        try {
            if ($data['capital_id'] == 0) {
                throw  new  Exception('清单id错误');
            }
            $capitalFind     = $capital->QueryOne($data['capital_id']);
            $capitalAllCount = $capital->whetherAgency(['ordesr_id' => $capitalFind['ordesr_id'], 'types' => 1,'envelopes_id'=>$capitalFind['envelopes_id']]);
            if ($capitalAllCount == 1) {
                throw  new  Exception('不允许删除,必须保留一个清单');
            }
            $capitalUpdate = ['capital_id' => $data['capital_id'], 'types' => 2, 'untime' => time()];
            $capital->isUpdate(true)->save($capitalUpdate);
            $capital->share($capitalFind['ordesr_id'], $capitalFind['envelopes_id']);
            db()->commit();
            $capitals = $capital->whetherAgency(['ordesr_id' => $capitalFind['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 1]);
            if ($capitals > 0) {
                $listOrderType = 1;
            } else {
                $listOrderType = 0;
                $envelopes->isUpdate(true)->save(['envelopes_id' => $capitalFind['envelopes_id'], 'purchasing_discount' => 0, 'purchasing_expense' => 0]);
            }
            $orderModel->orderAgency(['order_id' => $capitalFind['ordesr_id'], 'order_agency' => $listOrderType]);
            $this->pdf->put($capitalFind['ordesr_id'], 1, 0);
            sendOrder($capitalFind['ordesr_id']);
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }

    /**
     * 成交后基检删除
     */
    public function TransactionDeletion(Approval $approval, Capital $capital)
    {
        $data = Authority::param(['capital_id', 'quantity', 'reasonForDeduction']);
        db()->startTrans();
        try {
            $capitalFind    = $capital->QueryOne($data['capital_id']);
            if($capitalFind['acceptance'] !=0){
                throw  new  Exception('该项目已验收不允许删除');
            }
            $personal_price = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('order_id', $capitalFind['ordesr_id'])->whereNull('deleted_at')->sum('personal_price');
            $orderCapital   = Db::connect(config('database.zong'))->table('large_reimbursement')->where('order_id', $capitalFind['ordesr_id'])->where('status', 1)->sum('money');
            if ($personal_price < $orderCapital) {
                throw  new  Exception('不允许删除：大工地结算金额加过审大工地结算金额超过清单工资');
            }

            $reimbursement = db('reimbursement_relation')->join('reimbursement', 'reimbursement.id=reimbursement_relation.reimbursement_id')->where(['reimbursement_relation.capital_id' => $data['capital_id']])->field('reimbursement.status,reimbursement.order_id')->find();
            if (!empty($reimbursement)) {
                if ($reimbursement['status'] == 1 || $reimbursement['status'] == 0) {
                    throw  new  Exception('该代购主材已提交审批不能删除');
                }
            }
            if (isset($data['quantity']) && $data['quantity'] != 0) {
                $title        = $capitalFind['class_b'] . '减少方量到(' . $data['quantity'] . ')';
                $signed       = 1;
                $approvalType = 9;
            } else {
                $title        = $capitalFind['class_b'] . '项目减项(' . $this->us['username'] . ')';
                $signed       = 0;
                $approvalType = 6;
            }
            $work_time = Db::connect(config('database.db2'))->table('app_user_order_capital')->whereNull('deleted_at')->where('capital_id', $data['capital_id'])->value('work_time');
            if ($work_time != 0) {
                throw  new  Exception('师傅工时不为0无法删除');
            }
            $capitalUpdate = ['approve' => 3, 'modified_quantity' => $data['quantity'], 'reason_for_deduction' => $data['reasonForDeduction'], 'capital_id' => $data['capital_id'], 'signed' => $signed];
            $capital->isUpdate(true)->save($capitalUpdate);
            db()->commit();
            $this->inspect($capitalFind['ordesr_id'],$capitalFind['envelopes_id']);
            $approval->Reimbursement($data['capital_id'], $title, $this->us['username'], $approvalType);
            sendOrder($capitalFind['ordesr_id']);
            r_date([], 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }

    /**
     * 基检编辑
     */
    public function QuotationEditing(Common $common, Capital $capital, DetailedOptionValue $detailedOptionValue, CapitalValue $capitalValue, Detailed $detailed, OrderModel $orderModel)
    {
        $data = Authority::param(['capital_id', 'allMoney', 'fang', 'sectionTitle', 'unit', 'price', 'specsList', 'product_id', 'type', 'types', 'categoryName', 'projectTitle', 'agency', 'zhi', 'order_id', 'envelopes_id']);
        db()->startTrans();
        try {
            $ValueList = json_decode($data['specsList'], true);
            if ($data['types'] == 4) {

                $ValueId      = array_column($ValueList, 'option_value_id');
                $CapitalPrice = $common->newCapitalPrice($detailedOptionValue, $data['product_id'], $ValueId);
                if (!$CapitalPrice['code']) {
                    throw new Exception($CapitalPrice['msg']);
                }

                $CapitalPriceSection = $capital->priceSection($CapitalPrice['data']['price'], $CapitalPrice['data']['artificial'], $CapitalPrice['data']['sum'], $CapitalPrice['data']['sumMast'], $data['fang']);

                $data['sumMast']          = $CapitalPriceSection[2];
                $data['sum']              = $CapitalPriceSection[3];
                $data['price']            = $CapitalPrice['data']['price'];
                $data['artificial']       = $CapitalPrice['data']['artificial'];
                $data['categoryTitle']    = $CapitalPrice['data']['categoryTitle'];
                $data['toPrice']          = $CapitalPriceSection[1];
                $data['labor_cost_price'] = $CapitalPriceSection[0];
                $data['categoryTitle']    = $detailed->detailedCategoryTitle($data['product_id'])['title'];
                $id                       = $capital->newlyAdded($data, $data, 0);

                $list = $capitalValue->where('capital_id', $id)->find();
                if (!empty($list)) {
                    $capitalValue->where('capital_id', $id)->delete();
                }
                foreach ($ValueList as $item) {
                    $capitalValue->Add($item, $id);
                }
            } else {
                if (!empty($ValueList)) {
                    throw new Exception('请检查参数' . $data['types']);
                }
                if ($data['types'] == 0) {
                    $product_chan = db('product_chan')->where('product_id', $data['product_id'])->find();
                    $type         = 0;
                } elseif ($data['types'] == 1) {
                    $product_chan = db('detailed')->where('detailed_id', $data['product_id'])->find();
                    $type         = 1;
                } elseif ($data['types'] == 2) {
                    $product_chan['artificial'] = $data['price'];
                    $product_chan['rmakes']     = isset($data['remarks']) ? $data['remarks'] : '';
                    $type                       = 2;
                }
                $capital->oldAdded($product_chan, $data, $data['order_id'], $type, 0);
                $id = 0;

            }

            db()->commit();
            $this->pdf->put($data['order_id'], 1, 0);
            sendOrder($data['order_id']);
            r_date($id, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }

    }

    /**
     * 基检增项
     */
    public function AdditionalItem(Common $common, Capital $capital, DetailedOptionValue $detailedOptionValue, CapitalValue $capitalValue, Envelopes $envelopes, VisaForm $visaForm, EnvelopeRecords $envelopeRecords)
    {
        $data = Authority::param(['company', 'order_id', 'envelopes_id', 'gong']);
        db()->startTrans();
        try {
            if ($data['company']) {
                $ids = [];
                $op  = json_decode($data['company'], true);

                foreach ($op as $ke => $v) {
                    if (!empty($v['data'])) {
                        foreach ($v['data'] as $value) {
                            if (!isset($value['specsList'])) {
                                throw new Exception('请编辑清单包后提交');
                            }
                            $ValueList = $value['specsList'];

                            $value['fang']         = $value['square'];
                            $value['categoryName'] = $v['title'];
                            $value['product_id']   = $value['projectId'];
                            $value['unit']         = $value['company'];
                            $value['zhi']          = 1;
                            $value['type']         = 0;
                            $value['envelopes_id'] = $data['envelopes_id'];
                            if ($value['types'] == 4) {
                                $ValueId      = array_column($ValueList, 'option_value_id');
                                $CapitalPrice = $common->newCapitalPrice($detailedOptionValue, $value['product_id'], $ValueId);
                                if (!$CapitalPrice['code']) {
                                    throw new Exception($CapitalPrice['msg']);
                                }
                                $CapitalPriceSection = $capital->priceSection($CapitalPrice['data']['price'], $CapitalPrice['data']['artificial'], $CapitalPrice['data']['sum'], $CapitalPrice['data']['sumMast'], $value['fang']);

                                $data['sumMast']          = $CapitalPriceSection[2];
                                $data['sum']              = $CapitalPriceSection[3];
                                $data['price']            = $CapitalPrice['data']['price'];
                                $data['artificial']       = $CapitalPrice['data']['artificial'];
                                $data['categoryTitle']    = $CapitalPrice['data']['categoryTitle'];
                                $data['toPrice']          = $CapitalPriceSection[1];
                                $data['labor_cost_price'] = $CapitalPriceSection[0];
                                $id                       = $capital->newlyAdded($data, $value, 1);

                                foreach ($ValueList as $item) {
                                    $capitalValue->Add($item, $id);
                                }

                                if ($value['agency'] == 1) {
                                    $p1[] = $CapitalPriceSection[1];
                                } else {
                                    $p[] = $CapitalPriceSection[1];
                                }

                            } else {
                                if ($value['types'] == 0) {
                                    $product_chan = db('product_chan')->where('product_id', $value['product_id'])->find();
                                    $type         = 0;
                                } elseif ($value['types'] == 1) {
                                    $product_chan = db('detailed')->where('detailed_id', $value['product_id'])->find();
                                    $type         = 1;
                                } elseif ($value['types'] == 2) {
                                    $product_chan['artificial'] = $value['price'];
                                    $product_chan['rmakes']     = isset($value['remarks']) ? $value['remarks'] : '';
                                    $type                       = 2;
                                }
                                $id = $capital->oldAdded($product_chan, $value, $data['order_id'], $type, 1);
                            }

                            $ids[] = $id;
                        }
                    }


                }

            }

            $capital_id = $capital->where('ordesr_id', $data['order_id'])->where('capital.signed', 0)->where('capital.enable', 1)->where(function ($query) {
                $query->where('capital.types=2')->whereOr('capital.increment=1');
            })
                ->column('capital_id');
            $visaForm->addList($data['order_id'], $capital_id);
            if ($data['gong'] != 0) {
                $envelopesFind = $envelopes->getFind($data['envelopes_id']);
                $envelopes->isUpdate(true)->save(['envelopes_id' => $data['envelopes_id'], 'gong' => $data['gong'] + $envelopesFind['gong']]);
                $array = [];
                array_push($array, [
                        'previous_quantity' => $envelopesFind['gong'],
                        'post_quantity' => $data['gong'],
                        'reason' => '增项修改工期',
                        'type' => 1,
                        'envelopes_id' => $data['envelopes_id']
                    ]
                );

                $envelopeRecords->record($array);

                \db('app_user_order', config('database.db2'))->where('order_id', $data['order_id'])->update(['plan_work_time' => ($data['gong'] + $envelopesFind['gong']) * 24 * 60 * 60]);
            }
            db()->commit();
            $this->pdf->put($data['order_id'], 1, 0);
            $this->inspect($data['order_id'],$data['envelopes_id']);
            sendOrder($data['order_id']);
            r_date($id, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }

    }

    /*
     * 基建签证单
     */
    public function VisaDetails(VisaForm $visaForm)
    {
        $data    = Authority::param(['order_id', 'autograph']);
        $VisaPng = $visaForm->VisaDetails($data['order_id'], $data['autograph']);
        r_date($VisaPng, 200);

    }

    /*
    * 修改报价清单
    */
    public function QuotationList(Capital $capital)
    {
        $data = Authority::param(['give_remarks', 'capital_id', 'class_b']);
        $capital->isUpdate(true)->save(['class_b' => $data['class_b'], 'projectRemark' => $data['give_remarks'], 'capital_id' => $data['capital_id']]);
        r_date(null, 200);
    }

    /*
    * 修改报价分组名称
    */
    public function QuotationListEdit(Capital $capital)
    {
        $data       = Authority::param(['capital_id', 'categoryName']);
        $capital_id = json_decode($data['capital_id'], true);
        $capital->whereIn('capital_id', $capital_id)->update(['categoryName' => $data['categoryName']]);
        r_date(null, 200);
    }

    /*
    * 修改公共项目标题备注
    */
    public function TitleRemarks(Envelopes $envelopes)
    {
        $data = Authority::param(['envelopes_id', 'project_title', 'give_remarks']);
        $envelopes->isUpdate(true)->save(['envelopes_id' => $data['envelopes_id'], 'project_title' => $data['project_title'], 'give_remarks' => $data['give_remarks']]);
        r_date(null, 200);
    }

    /*
    * 修改公共项目赠送
    */
    public function GiftItems(Envelopes $envelopes)
    {
        $data = Authority::param(['envelopes_id', 'give_b']);

        $envelopes->isUpdate(true)->save(['envelopes_id' => $data['envelopes_id'], 'give_b' => substr($data['give_b'], 0, -1)]);
        r_date(null, 200);
    }

    /*
    * 修改公共项目工期
    */
    public function GiftItemsGong(Envelopes $envelopes, EnvelopeRecords $envelopeRecords)
    {
        $data            = Authority::param(['envelopes_id', 'gong', 'reason']);
        $envelopesSingle = $envelopes->getFind($data['envelopes_id']);
        $aggregate       = [];
        array_push($aggregate, [
            'previous_quantity' => $envelopesSingle['gong'],
            'post_quantity' => $data['gong'],
            'type' => 1,
            'reason' => $data['reason'],
            'envelopes_id' => $data['envelopes_id']
        ]);
        $envelopeRecords->record($aggregate);
        $envelopes->isUpdate(true)->save(['envelopes_id' => $data['envelopes_id'], 'gong' => $data['gong'], 'reason' => $data['reason']]);
        \db('app_user_order', config('database.db2'))->where('order_id', $envelopesSingle['ordesr_id'])->update(['plan_work_time' => $data['gong'] * 24 * 60 * 60]);
        r_date(null, 200);
    }

    /*
    * 修改报价清单
    */
    public function MarkCollaboration(Capital $capital)
    {

        $data = Authority::param(['cooperation', 'capital_id']);
        $capital->isUpdate(true)->save(['cooperation' => $data['cooperation'], 'capital_id', $data['capital_id']]);
        r_date(null, 200);
    }

    /**
     * 基检更新公共
     */
    public function AmountModification(Envelopes $envelopes, Capital $capital, EnvelopeRecords $envelopeRecords)
    {
        $data = Authority::param(['envelopes_id', 'purchasing_discount', 'purchasing_expense', 'give_money', 'expense']);
        db()->startTrans();
        try {
            $envelopesSingle = $envelopes->getFind($data['envelopes_id']);
            $capital         = $capital->get(['ordesr_id' => $envelopesSingle['ordesr_id'], 'types' => 1, 'enable' => 1]);
            $result          = [];
            foreach ($capital as $key => $info) {
                $result[$info['agency']][] = $info;
            }
            //            if (isset($result[0]) && $result[0] != 0) {
//                $cap = array_sum(array_column($result[0], 'to_price'));
//                if (($cap * config('give_money')) < $data['give_money']) {
//                    throw  new  Exception('优惠金额不能大于订单总价的10%');
//                }
//            }

//            if (count($result) == 2) {
//                $cap = array_sum(array_column($result[1], 'to_price'));
//                if (($cap * config('purchasing_discount')) < $data['purchasing_discount']) {
//                    throw  new  Exception('优惠金额不能大于代购订单总价的10%');
//                }
//            }

            $purchasing_discount = round($data['purchasing_discount'], 2);
            $purchasing_expense  = round($data['purchasing_expense'], 2);
            $give_money          = round($data['give_money'], 2);
            $expense             = round($data['expense'], 2);
            $cli                 = new Client();
            if ($envelopesSingle['purchasing_discount'] != $purchasing_discount || $envelopesSingle['purchasing_expense'] != $purchasing_expense) {
                //（改变后的管理费-优惠）-（改变前的管理费-优惠）
                $moeny = ($purchasing_expense - $purchasing_discount) - ($envelopesSingle['purchasing_expense'] - $envelopesSingle['purchasing_discount']);
                $list  = json_encode(["order_id" => $envelopesSingle['ordesr_id'], "type" => 2, 'money' => $moeny]);
                $cli->index($list, $cli::order_queue, $cli::order_routingkey);
            }
            if ($envelopesSingle['give_money'] != $give_money || $envelopesSingle['expense'] != $expense) {
                $moeny = ($expense - $give_money) - ($envelopesSingle['expense'] - $envelopesSingle['give_money']);
                $list  = json_encode(["order_id" => $envelopesSingle['ordesr_id'], "type" => 1, 'money' => $moeny]);
                $cli->index($list, $cli::order_queue, $cli::order_routingkey);
            }
            $oi        = [
                'give_money' => $give_money,//优惠金额
                'purchasing_discount' => $purchasing_discount,
                'expense' => $expense,
                'purchasing_expense' => $purchasing_expense,
                'envelopes_id' => $data['envelopes_id']
            ];
            $aggregate = [];

            if ($envelopesSingle['purchasing_discount'] != $purchasing_discount) {
                array_push($aggregate, [
                    'previous_quantity' => $envelopesSingle['purchasing_discount'],
                    'post_quantity' => $purchasing_discount,
                    'type' => 2,
                    'reason' => '变更代购主材优惠金额',
                    'envelopes_id' => $data['envelopes_id']
                ]);
            }

            if ($envelopesSingle['purchasing_expense'] != $purchasing_expense) {
                array_push($aggregate, [
                    'previous_quantity' => $envelopesSingle['purchasing_expense'],
                    'post_quantity' => $purchasing_expense,
                    'type' => 2,
                    'reason' => '变更代购主材管理费',
                    'envelopes_id' => $data['envelopes_id']
                ]);
            }

            if ($envelopesSingle['give_money'] != $give_money) {
                array_push($aggregate, [
                    'previous_quantity' => $envelopesSingle['give_money'],
                    'post_quantity' => $give_money,
                    'type' => 2,
                    'reason' => '变更主材优惠金额',
                    'envelopes_id' => $data['envelopes_id']
                ]);
            }
            if ($envelopesSingle['expense'] != $expense) {
                array_push($aggregate, [
                    'previous_quantity' => $envelopesSingle['expense'],
                    'post_quantity' => $expense,
                    'type' => 2,
                    'reason' => '变更主材管理费',
                    'envelopes_id' => $data['envelopes_id']
                ]);
            }

            if (!empty($aggregate)) {

                $envelopeRecords->record($aggregate);
            }

            $envelopes->isUpdate(true)->save($oi);

            db()->commit();
            sendOrder($envelopesSingle['ordesr_id']);
            $this->pdf->put($envelopesSingle['ordesr_id'], 1, 0);
            r_date(null, 200);

        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }

    }

    /*
     * 数据同步
     */
    public function DataMatching(DetailedOptionValue $detailedOptionValue, Common $common, Capital $capital)
    {
        $data        = Authority::param(['projectJson']);

        $list=null;

        if(!empty(json_decode($data['projectJson'], true))){
            $projectJson = json_decode($data['projectJson'], true);
            $list        = $detailedOptionValue->matching($projectJson);
            foreach ($list as $k => $l) {
                foreach ($l['data'] as $o => $v) {
                    $is_compose = db('detailed')->where('detailed_id', $v['projectId'])->value('display');
                    if ($is_compose == 1) {
                        if (!empty($v['specsList']) && $v['square'] != 0) {
                            $ValueId             = array_column($v['specsList'], 'option_value_id');
                            $CapitalPrice        = $common->newCapitalPrice($detailedOptionValue, $v['projectId'], $ValueId);
                            $CapitalPriceSection = $capital->priceSection($CapitalPrice['data']['price'], $CapitalPrice['data']['artificial'], $CapitalPrice['data']['sum'], $CapitalPrice['data']['sumMast'], $v['square']);
                            if (!$CapitalPrice['code']) {
                                r_date(null, 300, $CapitalPrice['msg']);
                            }

                            $list[$k]['data'][$o]['projectMoney'] = $CapitalPriceSection[3];
                            $list[$k]['data'][$o]['allMoney']     = $CapitalPriceSection[1];
                        }
                    } else {
                        unset($list[$k]['data'][$o]);

                    }


                }

            }
            foreach ($list as $k => $l) {
                $po               = array_merge($l['data']);
                $list[$k]['data'] = $po;
            }
        }



        r_date($list, 200);
    }
    /*
     * 检查有没有代购
     */
    public function inspect($orderId,$envelopes_id){
        $capitals = (new  capital)->whetherAgency(['ordesr_id' => $orderId, 'types' => 1, 'enable' => 1, 'agency' => 1]);
        if ($capitals > 0) {
            $listOrderType = 1;
        } else {
            $listOrderType = 0;
            (new envelopes)->isUpdate(true)->save(['envelopes_id' => $envelopes_id, 'purchasing_discount' => 0, 'purchasing_expense' => 0]);
        }
        (new orderModel)->orderAgency(['order_id' => $orderId, 'order_agency' => $listOrderType]);
    }

}